<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <el-form-item label="用户昵称" prop="nickName">
            <el-input v-model="baTable.form.items!.nickName" />
            <div class="block-help">
              区别登录使用的名称 如本名或者姓氏加职称
            </div>
          </el-form-item>
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="baTable.form.items!.userName"
              placeholder="登录所使用的用户名"
              maxlength="30"
            />
            <div class="block-help">登录所使用的用户名 只能输入数字和英文</div>
          </el-form-item>
          <el-form-item
            v-if="baTable.form.items!.userId == undefined"
            label="用户密码"
            prop="password"
          >
            <el-input
              v-model="baTable.form.items!.password"
              placeholder="请输入用户密码"
              type="password"
              maxlength="20"
              show-password
            />
          </el-form-item>
          <el-form-item label="联系方式" prop="phonenumber">
            <el-input
              v-model="baTable.form.items!.phonenumber"
              placeholder="请输入手机号码"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="baTable.form.items!.email"
              placeholder="请输入邮箱"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="baTable.form.items!.sex">
              <el-radio
                v-for="(item, index) in state.genderDictArr"
                :key="index"
                :label="Number(item.dictValue)"
                border
                >{{ item.dictLabel }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <FormItem
            prop="status"
            v-if="baTable.form.items!.menuType !== 'F'"
            label="状态"
            v-model="baTable.form.items!.status"
            type="radio"
            :data="{
              content: { 0: '正常', 1: '停用' },
              childrenAttr: { border: true },
            }"
          />

          <el-form-item label="岗位" prop="postIds">
            <el-select
              v-model="baTable.form.items!.postIds"
              multiple
              placeholder="请选择岗位"
            >
              <el-option
                v-for="item in state.postOptions"
                :key="item.postId"
                :label="item.postName"
                :value="item.postId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色" prop="roleIds">
            <el-select
              v-model="baTable.form.items!.roleIds"
              multiple
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in state.roleOptions"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="baTable.form.items!.deptId"
              :data="state.deptOptions"
              :props="{
                label: 'label',
                value: 'id',
                children: 'children',
              }"
              :render-after-expand="false"
              check-strictly
            />
          </el-form-item>
          <!-- <el-form-item label="工序列表" prop="skill">
            <el-select
              v-model="state.skill"
              value-key="id"
              multiple
              placeholder="可自定义设备工序"
              @change="ProcessChange"
            >
              <el-option
                v-for="item in state.processOptions"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
            <div class="block-help" style="width: 100%">对标员工技能</div>
          </el-form-item> -->
          <!-- <FormItem
            prop="userType"
            label="用户类型"
            v-model="baTable.form.items!.userType"
            type="radio"
            :data="{
              content: { 1: '区域', 2: '企业' },
              childrenAttr: { border: true },
            }"
          />
          <div v-if="baTable.form.items!.userType">
            <el-form-item
              label="所属企业"
              prop="companyid"
              v-if="baTable.form.items!.userType == 2"
            >
              <el-input
                v-model="filterText"
                placeholder="输入关键字进行过滤"
                style="background: whitesmoke"
              />
              <el-scrollbar
                ref="verticalMenusRef"
                class="vertical-menus-scrollbar"
                style="border: 1px solid #dcdfe6; width: 100%"
              >
                <el-tree
                  ref="treeRef2"
                  class="filter-tree"
                  :data="state.companyOptions"
                  :props="{ label: 'name', value: 'id' }"
                  node-key="id"
                  show-checkbox
                  default-expand-all
                  :default-checked-keys="
                    baTable.form.operate == 'edit'
                      ? [baTable.form.items.companyid]
                      : []
                  "
                  :filter-node-method="filterNode"
                  @check="userCheck"
                />
              </el-scrollbar>
            </el-form-item>
            <el-form-item
              v-loading="state.regionLoading"
              label="所属区域"
              prop="regions"
              v-if="baTable.form.items!.userType == 1"
            >
              <div style="width: 100%">
                <el-checkbox
                  v-model="state.menuExpand"
                  @change="handleCheckedTreeExpand($event, 'menu')"
                  >展开/折叠</el-checkbox
                >
                <el-checkbox
                  v-model="state.menuNodeAll"
                  @change="handleCheckedTreeNodeAll($event, 'menu')"
                  >全选/全不选</el-checkbox
                >
                <el-checkbox
                  v-model="state.menuCheckStrictly"
                  @change="handleCheckedTreeConnect($event, 'menu')"
                  >父子联动</el-checkbox
                >
              </div>
              <el-tree
                ref="treeRef"
                class="tree-border"
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? baTable.form.items.regions
                    : []
                "
                show-checkbox
                :check-strictly="!state.menuCheckStrictly"
                node-key="areaId"
                :props="{
                  children: 'children',
                  label: 'areaName',
                  value: 'areaId',
                }"
                empty-text="加载中，请稍候"
                :data="state.regionOptions"
              >
                <template #default="{ node, data }">
                  <span class="custom-tree-node">
                    <span @click="append(data)">{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </el-form-item>
          </div> -->
          <el-form-item label="备注">
            <el-input
              @keyup.enter.stop=""
              @keyup.ctrl.enter="baTable.onSubmit(formRef)"
              v-model="baTable.form.items!.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch, computed } from "vue";
import type baTableClass from "@/utils/baTable";
import type { ElForm, FormRules, ElTree } from "element-plus";
import FormItem from "@/components/formItem/index.vue";
import { useUser } from "@/store/backend/SysM/user";
import { useRegion } from "@/store/backend/SysM/region";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import { useDictionary } from "@/store/backend/tool/dictionary";

const user = useUser();
const config = useConfig();
const region = useRegion();
const dictionary = useDictionary();

//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const bomP = inject("bomP") as any;
const treeRef = ref<InstanceType<typeof ElTree>>();
const treeRef2 = ref<InstanceType<typeof ElTree>>();
const formRef = ref<InstanceType<typeof ElForm>>();
type Option = {
  id: number;
  label: string;
  children: Option[];
};

const filterText = ref("");
const filterNode = (value: string, data: any) => {
  console.log(value, data);

  if (!value) return true;
  return data.name.includes(value);
};
const state: {
  deptOptions: Option[];
  postOptions: anyObj[];
  roleOptions: anyObj[];
  regionOptions: anyObj[];
  companyOptions: anyObj[];
  regionLoading: boolean;
  processOptions: anyObj[];
  id: number;
  menuExpand: boolean;
  menuNodeAll: boolean;
  menuCheckStrictly: boolean;
  genderDict: anyObj;
  genderDictArr: anyObj[];
  skill: anyObj[];
} = reactive({
  deptOptions: [], //部门列表
  postOptions: [], //岗位列表
  roleOptions: [], //角色列表
  regionOptions: [], //区域列表
  companyOptions: [], //企业列表
  regionLoading: false, //区域列表展示前的过渡动画
  id: 0,
  menuExpand: false,
  menuNodeAll: false,
  menuCheckStrictly: false,
  genderDict: {}, //用户性别字典项
  genderDictArr: [], //用户性别字典项
  processOptions: [], //工序列表
  skill: [], //工序列表
});
const userCheck = (MouseEvent: any, object: any, Node: any, element: any) => {
  baTable.form.items!.companyid = MouseEvent.id;
};
// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value: any, type: any) => {
  let treeList = region.originData; //原始区域数据
  for (let i = 0; i < treeList.length; i++) {
    treeRef.value!.store.nodesMap[treeList[i].areaId].expanded = value;
  }
};
// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: any, type: any) => {
  //原始区域数据
  treeRef.value!.setCheckedNodes(value ? (region.originData as any) : []);
};
// 树权限（父子联动）
const handleCheckedTreeConnect = (value: any, type: any) => {
  state.menuCheckStrictly = value ? true : false;
};

// 表单验证
const rules = reactive<FormRules>({
  nickName: [
    {
      required: true,
      message: "用户昵称必填",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "需要设置用户密码",
      trigger: "blur",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择用户状态",
      trigger: "blur",
    },
  ],
  deptId: [
    {
      required: true,
      message: "请选择用户归属部门",
      trigger: "blur",
    },
  ],
  userName: [
    {
      required: true,
      message: "登录所使用的用户名",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        const title = /^[\a-\z\A-\Z0-9\u4e00-\u9fe5]+$/; //中英文
        // const title = /^[\a-\z\A-\Z0-9]+$/;
        if (!title.test(value)) {
          callback(new Error("只能输入数字和英文"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  postIds: [
    {
      required: true,
      message: "请选择岗位",
      trigger: "blur",
    },
  ],
  roleIds: [
    {
      required: true,
      message: "请选择角色",
      trigger: "blur",
    },
  ],
  phonenumber: [
    {
      required: true,
      message: "联系方式",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("手机号格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  // email: [
  //   {
  //     required: true,
  //     message: "请输入邮箱",
  //     trigger: "blur",
  //   },
  //   {
  //     validator: function (rule, value, callback) {
  //       if (
  //         /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(value) ==
  //         false
  //       ) {
  //         callback(new Error("邮箱格式错误"));
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: "blur",
  //   },
  // ],
  userType: [
    {
      required: true,
      message: "用户类型必选",
      trigger: "blur",
    },
  ],
  regions: [
    {
      required: true,
      validator: (rule: any, val: string, callback: Function) => {
        let ids = getCheckeds() ? getCheckeds() : [];
        if (ids!.length <= 0) {
          return callback(new Error("请选择区域"));
        }
        return callback();
      },
    },
  ],
  companyid: [
    {
      required: true,
      message: "企业用户至少选择一个企业",
      trigger: "blur",
    },
  ],
});

//选择技能/工序
const ProcessChange = (val: any) => {
  // baTable.form.items!.skill = val.name;
  console.log("选择技能/工序", val);
  let skillId = [];
  let skill = [];
  for (let i = 0; i < val.length; i++) {
    skillId.push(val[i].id);
    skill.push(val[i].name);
  }
  baTable.form.items!.skillId = skillId;
  baTable.form.items!.skill = skill;
};

const append = (data: any) => {
  console.log("data", data);
  baTable.form.items!.regionName = data.areaName;
};
const getCheckeds = () => {
  return treeRef.value
    ?.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};

//获取区域列表
const getRegionListByRole = () => {
  region
    .getRegionByRole()
    .then((res: any) => {
      state.regionOptions = res;
      state.regionLoading = false;
    })
    .catch(() => {
      state.regionLoading = false;
    });
};
const getCompanyList = () => {
  const business = useBusiness();
  const { companyList } = business;
  if (companyList.length === 0) {
    business.getCompanyList().then((res: any) => {
      state.companyOptions = res.rows;
      console.log("state.companyOptions", state.companyOptions);
    });
  } else {
    state.companyOptions = companyList;
    console.log("state.companyOptions", state.companyOptions);
  }
};

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});

const getGenderdict = () => {};
getGenderdict();

onMounted(() => {
  //获取岗位角色与部门 区域 四大数据
  user.getDept().then((res: any) => {
    state.deptOptions = res.data;
    console.log("state.deptOptions", state.deptOptions);
  });
  user.getPostRole().then((res: any) => {
    state.postOptions = res.posts;
    state.roleOptions = res.roles;
    console.log("角色", state.roleOptions, "岗位", state.postOptions);
  });
  //获取用户性别字典项
  dictionary.getDictInfo("sys_user_sex").then((res: any) => {
    state.genderDictArr = res;
  });
  //获取工序字典数据
  bomP.getRouteList({ pageSize: 1000 }).then((res: any) => {
    console.log("获取工序列表", res);
    state.processOptions = res.rows;
  });
  //显示员工工序/技能
  setTimeout(() => {
    state.skill = baTable.form.items!.skill;
  }, 500);
});

watch(
  () => baTable.form.items!.userType,
  (newValue, oldValue) => {
    if (newValue === "1") {
      //区域用户获取区域数据
      getRegionListByRole();
      state.regionLoading = true;
    } else if (newValue === "2") {
      //企业用户获取企业数据
      getCompanyList();
    }
  },
  {
    immediate: true, // 值如果是true会打开首次监听
  }
);
watch(filterText, (val) => {
  treeRef2.value!.filter(val);
});
defineExpose({
  getCheckeds,
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  height: v-bind(overviewMenusScrollbarHeight);
}
.tree-border {
  width: 100%;
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #fff none;
  border-radius: 4px;
}
</style>
